const EventClassIdRegex = /#([^\s]+)/;

import * as vscode from 'vscode';

export class EventBlock {

    public RawText: string;
    public static BlockTag = 'event';
    public RawContent: string[] = [];
    public title: string = '';
    public time!: number;
    public timeSystemId: string = '';
    public timeSystem: string = '';
    public timeText: string = '';
    public groupId: string = '';
    private link: string[] = [];
    public content: string[] = [];
    public LineStartNumber: number = 0;
    public LineEndNumber: number = 0;
    public docPath: string = '';


    constructor(text: string) {
        this.RawText = text;
        this.RawContent.push(text);
    }

    public static isEventBlock(text: string) {
        return text.startsWith('> ');
    }

    public addLine(line: string) {
        this.RawContent.push(line);

        if (line.startsWith('http://') || line.startsWith('https://') || line.startsWith('file://')) {
            this.link.push(line);
        } else if (line.startsWith('file=')) {
            this.docPath = line.substring(5);
        } else {
            this.content.push(line);
        }
    }

    public freeze() {
        const noWrapText = this.RawText.substring(1).trim();
        try {
            const parts = noWrapText.split(' ').map(item => item.trim());

            // 提取时间原文本
            if (parts.length > 0) {
                const timeStr = parts[0].split('@');
                this.timeText = timeStr[0];

                if (timeStr.length > 1) {
                    this.timeSystemId = timeStr[1];
                } else {
                    this.timeSystemId = 'system';
                    this.timeSystem = '';

                    // 默认时间系统
                    if (this.timeText.startsWith('-')) {
                        const x = this.timeText.substring(1).split('-').map(x => parseInt(x));
                        this.time = getTime(x) * -1;
                    } else {
                        const x = this.timeText.split('-').map(x => parseInt(x));
                        this.time = getTime(x);
                    }
                }
            }

            // 提取标题
            if (parts.length > 1 && !parts[1].startsWith('#')) {
                this.title = parts[1].trim();
            }

            const classDefs = parts.filter(p => p.startsWith('#'));
            // 提取分组
            this.groupId = classDefs.length > 0 ? classDefs[0].substring(1) : 'DEFAULT';

        } catch (error) {
            vscode.window.showErrorMessage(`事件解析错误：${this.RawText}`);
        }
    }

    /**
     * 检查当前事件块是否包含指定关键词
     * @param keyword 要搜索的关键词
     * @returns 如果标题或内容任意一行包含关键词则返回true，否则返回false
     */
    public containsKeyword(keyword: string) {
        return this.title.includes(keyword) || this.content.some(line => line.includes(keyword));
    }

    /**
     * 获取事件块数据
     * @returns 包含时间、时间文本、时间系统、分组ID、链接、标题和内容的对象
     */
    public getData() {

        const content = this.content.join('\n');
        const tags = extractTags(content);

        return {
            time: this.time,
            timeText: this.timeText,
            timeSystem: this.timeSystem,
            groupId: this.groupId,
            link: this.link,
            title: this.title,
            content,
            docPath: this.docPath,
            tags
        };
    }
}


function getTime(x: number[]) {
    if (x.length < 3) {
        x.push(1);
    }
    if (x.length < 3) {
        x.push(1);
    }
    return (x[0] * 10000 + x[1] * 100 + x[2]);
}


const TagRegex = /#[\u4e00-\u9fa5a-zA-Z0-9_\-]+/g
const TagRegex2 = /^#[\u4e00-\u9fa5a-zA-Z0-9_\-]+$/


function extractTags(text: string) {
    // 匹配所有以#开头，后跟中英文数字的连续字符序列
    const matches = text.match(TagRegex) || [];

    // 过滤结果：长度≤10且内容不包含符号
    return matches.filter(tag =>
        tag.length <= 10 &&
        // 二次验证内容部分（不含#）仅含中英文数字
        TagRegex2.test(tag)).map(tag => tag.slice(1));
}
